import { login, getUserInfo, getUserDetailById } from '@/api/user.js'
import * as auth from '@/utils/auth.js'
import { resetRouter } from '@/router/index'
export default {
  namespaced: true,
  state: {
    token: auth.getToken() || '',
    user: {}
  },
  mutations: {
    // 存token
    setToken (state, token) {
      state.token = token
      auth.setToken(token)
    },
    // 删除token
    delToken (state) {
      state.token = ''
      auth.removeToken()
    },
    // 给user赋值
    setUser (state, user) {
      state.user = user
    },
    // 清空user
    delUser (state) {
      state.user = {}
    }
  },
  actions: {
    // 请求数据获取token
    async getTokenActions (ctx, loginForm) {
      const res = await login(loginForm)
      ctx.commit('setToken', res)
    },
    // 请求user数据
    async getUserActions ({ commit }) {
      const user = await getUserInfo()
      const photo = await getUserDetailById(user.userId)
      commit('setUser', { ...user, ...photo })
      return user.roles
    },
    // 退出登录
    logoutActions ({ commit }) {
      commit('delToken')
      commit('delUser')
      resetRouter()
      commit('menu/setList', [], { root: true })
    }
  }
}
